/**
 * 
 */
package org.shortestpath.core.util;

import org.shortestpath.core.Point;
import java.util.Collections;
import java.util.Comparator;
import java.util.Vector;


/**
 * Class for helping up dijkrast algo by providing utility methods.
 * 
 * @author Thilani
 *
 */
public class DijkrastUtil {
	
	/**
	 * Calculates the distance between two vertexes
	 * 
	 * @param vertexFrom
	 * @param vertexTo
	 * @return
	 */
	public static double calculateDistance(Point vertexFrom, Point vertexTo){
		double xDistance = Math.abs(vertexTo.getX() - vertexFrom.getX());
		double yDistance = Math.abs(vertexTo.getY() - vertexFrom.getY());
		return Math.sqrt(Math.pow(xDistance, 2) + Math.pow(yDistance, 2));
	}
	
	public void getOverlapRoad(){
		
	}
	
	/**
	 * Initializes the single source dijkrast algo by initializing distance to infinity and 
	 * from node to null. Finally set the distance of source to zero
	 * @param vertexes
	 * 		All the vertexes for build the graph
	 * @param source
	 * 		The starting node
	 */
	public static void initSingleSource(Vector<Point> vertexes, Point source){
		for (int i=0; i< vertexes.size(); i++){
			Point vertex = vertexes.elementAt(i);
			vertex.setDistance(Double.MAX_VALUE);
		}
		source.setDistance(0);
	}
	
	/**
	 * Perform the relaxation for dijkrast algo
	 * 
	 * @param vertexFrom
	 * @param vertexTo
	 */
	public static void doRelax(Point vertexFrom, Point vertexTo){
		double relaxDistance = vertexFrom.getDistance() + calculateDistance(vertexFrom, vertexTo);
		if (vertexTo.getDistance() > relaxDistance){
			vertexTo.setDistance(relaxDistance);
			vertexTo.setFrom_node(vertexFrom);
		}
	}
	
	/**
	 * Extract the minimum distance vertex from the vector
	 * 
	 * @param vertexes
	 * @return
	 */
	public static Point extractMin(Vector<Point> vertexes){
		Collections.sort(vertexes, new Comparer());
		return vertexes.elementAt(0);
	}
	
	public void getAdjVertexes(Point vertex){
		
	}
}

/**
 * The comparer class for sort vector against the distance
 * 
 * @author Thilani
 *
 */
class Comparer implements Comparator {
    public int compare(Object obj1, Object obj2)
    {
    	double i1 = ((Point)obj1).getDistance();
    	double i2 = ((Point)obj2).getDistance();
    	return (int) ((Math.abs(i1) - Math.abs(i2))*1000);
    }
}

